from simpy import Resource, Environment

from x_pc.core import Device, DeviceCost, System
from x_pc.model.model import Task


class JCB(Device, DeviceCost):
    """
    302 机械手拆板站台
    机拆板(JCB)
    """
    COST_TIME = 10
    # 资源
    resource: Resource = None

    def __init__(self, env: Environment, name: str):
        super().__init__(env, name)
        self.resource = Resource(env)

    def cost(self, *args, **kwargs) -> float:
        return self.COST_TIME


class JCBSystem(System):
    """
    机械手拆板站台 系统
    """
    # JCB数量
    JCB_NUMS = 1
    # JCB列表
    jcb_list: list[JCB] = []

    def __init__(self, env: Environment, name: str, code: str = None):
        super().__init__(env, name, code)
        self.__init_jcb_list()

    def __init_jcb_list(self):
        self.jcb_list = [JCB(self.env, f'机拆板-{_ + 1}') for _ in range(self.JCB_NUMS)]

    def run_task(self, task: Task):
        if not self.jcb_list:
            while self.running:
                yield self.env.timeout(1)
                if self.jcb_list:
                    break
        #
        jcb = self.jcb_list.pop(0)
        with jcb.resource.request() as req:
            yield req
            #
            process = task.process
            process.begin_ts = self.env.now
            process.begin_pos = jcb.name
            #
            yield self.env.timeout(jcb.cost())
            #
            process.end_ts = self.env.now
            process.device_code = jcb.name
            # 根据任务类型的不同，将任务分发至不同的设备
            process.end_pos = None
